package com.zsinfo.guoss.supplier.utils.upaiyun;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.File;


public class UpLoadUtil extends AsyncTask<String, Void, String> {
	private String DEFAULT_DOMAIN = "zhangshuoinfo.b0.upaiyun.com";// 空间域名
	private String API_KEY = "LaubRPoyoLzq9tJ82/z+RSmFUVY="; // 表单api验证密钥
	private String BUCKET = "zhangshuoinfo";// 空间名称
	private long EXPIRATION = System.currentTimeMillis() / 1000 + 1000 * 5 * 10; // 过期时间，必须大于当前时间
	private String type;
	@SuppressWarnings("unused")
	private String uploadPath;
	private Context context;
	private CallBack callBack;
	private ProgressDialog dialog;

	public UpLoadUtil(String type, Context context, CallBack callBack) {
		super();
		this.type = type;
		this.context = context;
		this.callBack = callBack;
	}

	@Override
	protected void onPreExecute() {
		dialog = new ProgressDialog(context);
		dialog.setMessage("正在上传中,请稍等...");
		dialog.show();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected String doInBackground(String... params) {
		if (TextUtils.isEmpty(params[0])) {
			return "";
		}

		String string = null;
		Log.i("test", "文件大小：" + new File(params[0]).length() / (1024 * 1024f)
				+ "M");

		try {
			// 设置服务器上保存文件的目录和文件名，如果服务器上同目录下已经有同名文件会被自动覆盖的。
			String SAVE_KEY = File.separator + type + File.separator
					+ System.currentTimeMillis() + "." + type;

			// 取得base64编码后的policy
			String policy = UpYunUtils.makePolicy(SAVE_KEY, EXPIRATION, BUCKET);

			// 根据表单api签名密钥对policy进行签名
			// 通常我们建议这一步在用户自己的服务器上进行，并通过http请求取得签名后的结果。
			String signature = UpYunUtils.signature(policy + "&" + API_KEY);

			long startTime = System.currentTimeMillis();
			Log.i("test", "开始上传：" + startTime);
			// 上传文件到对应的bucket中去。
			string = DEFAULT_DOMAIN
					+ Uploader.upload(policy, signature, BUCKET, params[0]);

			Log.i("test", "上传完成：" + (System.currentTimeMillis() - startTime)
					+ "ms");

		} catch (UpYunException e) {
			e.printStackTrace();
			Log.i("test", "异常了..." + e.getMessage());
		}

		return string;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		uploadPath = result;
		if (result != null) {
			Log.i("test", "上传成功,访问地址为：" + result);
			Toast.makeText(context, "上传成功,访问地址为：" + result, Toast.LENGTH_SHORT)
					.show();
			callBack.Send(result);
		} else {
			Log.i("test", "上传图片失败");
			Toast.makeText(context, "上传图片失败", Toast.LENGTH_SHORT).show();
		}
		dialog.dismiss();
	}

	public interface CallBack {
		void Send(String str);
	}
}
